package com.w.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.w.api.GoodsInnerApi;
import com.w.api.UserInnerApi;
import com.w.base.Result;
import com.w.dto.OrderDto;
import com.w.order.entity.OrderEntity;
import com.w.order.mapper.OrderMapper;
import com.w.order.service.OrderService;
import com.w.vo.GoodsVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author w²
 * @since 2020-09-27
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {

    @Autowired
    private GoodsInnerApi goodsInnerApi;

    @Autowired
    private UserInnerApi userInnerApi;

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 创建订单
     *
     * @param orderDto 订单信息
     * @return 创建结果
     */
    @Override
    @GlobalTransactional(rollbackFor = RuntimeException.class)
    public Result createOrder(OrderDto orderDto) {
        // 查询商品信息
        GoodsVo goodsVo = goodsInnerApi.selectGoods(orderDto.getGoodsId());
        // 计算订单价格 = 商品单价 * 购买数量
        BigDecimal orderPrice = goodsVo.getPrice().multiply(new BigDecimal(orderDto.getGoodsCount()));
        // 创建订单
        orderDto.setOrderPrice(orderPrice);
        orderDto.setAddTime(LocalDateTime.now());
        OrderEntity orderEntity = new OrderEntity();
        BeanUtil.copyProperties(orderDto, orderEntity);
        Boolean createOrderFlag= insertOrder(orderEntity);
        if (!createOrderFlag) {
            throw new RuntimeException("订单创建失败");
        }
        // 扣减库存
        goodsInnerApi.deductStock(orderDto.getGoodsId(), orderDto.getGoodsCount());
        // 扣减余额
        userInnerApi.reduceBalance(orderDto.getUserId(), orderPrice);
        return Result.success("订单创建成功");
    }

    /**
     * 创建订单信息
     *
     * @param orderEntity 订单信息
     * @return 创建结果
     */
    private Boolean insertOrder(OrderEntity orderEntity) {
        return orderMapper.insert(orderEntity) > 0;
    }

}
